import React from "react";
import { Table } from "antd";
import  SearchHeader from "./SearchHeader";
import styles from "./SearchHeader.less";

export default class SearchTable extends React.Component {
  static defaultProps = {
    showHeader: true,
    quickJumpLabel: '到第',
  }

  constructor(props) {
    super(props);
    this.tableRef = React.createRef();
  }

  componentDidUpdate() {
    const { quickJumpLabel } = this.props;
    if (!quickJumpLabel) { return }
    const table = this.tableRef.current;
    if (table) {
      const jumpElm = table.querySelector('.ant-pagination-options-quick-jumper');
      if (!jumpElm) { return };
      const { childNodes } = jumpElm;
      if (childNodes && childNodes.length > 0 ) {
        const textNode = childNodes[0];
        if (textNode && textNode.nodeType === Element.TEXT_NODE) {
          textNode.textContent = quickJumpLabel;
        }
      }
    }
  }

  handleReset = () => {
    if (this.searchHeader) {
      this.searchHeader.onReset()
    }
  }

  refSearch = (r) => {
    if (r) {
      this.searchHeader = r;
    }
  }

  render() {
    const {
      formConfig,
      handleSearch,
      tableProps,
      searchLoading,
      showHeader,
    } = this.props;
    const buttonLoading = searchLoading !== undefined ? searchLoading : tableProps.loading
    return (
      <>
        { showHeader ? (
          <SearchHeader
            {...(buttonLoading !== undefined ?
              { searchLoading: buttonLoading } : {}
            )}
            formConfig={formConfig}
            wrappedComponentRef={this.refSearch}
            onSearch={handleSearch}
          />
        ): null
        }
        <div
          ref={this.tableRef}
          className={styles.table}
        >
          <Table {...tableProps} />
        </div>
      </>
    );
  }
}

export function getTableProps(options) {
  const { pagination, ...rest } = options;
  return {
    pagination: {
      pageSizeOptions: ['10', '20', '30', '40'],
      showQuickJumper: { goButton: <span className={styles.goPage}>确定</span> },
      showSizeChanger: true,
      showTotal: (total) => `共有${total}条`,
      ...pagination,
    },
    ...rest,
  }
}
